package com.example.publishDemo.Controller.imgUpload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/cover")
public class CoverUploadController {

    private static final String PRODUCT_FILE_PREFIX = "D:\\IO\\cover\\";
    private static final String SERVER_PREFIX = "http://localhost:8888/";

    //获取文章的封面
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        if (!FileUtil.isDirectory(PRODUCT_FILE_PREFIX)) {
            FileUtil.mkdir(PRODUCT_FILE_PREFIX);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(PRODUCT_FILE_PREFIX);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try{
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(avatar,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(PRODUCT_FILE_PREFIX + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败!");
        }
    }

    @PostMapping("/coverUpload")
    public Map<String,Object> upload(@RequestPart("file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();

        if (file.isEmpty()) {
            map.put("errno", 1);
            return map;
        }
        String name = UUID.randomUUID().toString().replaceAll("-","");
        File path = new File(PRODUCT_FILE_PREFIX + name + getSuffix(file));
        if(!path.getParentFile().exists()) path.getParentFile().mkdirs(); //如果没有就创建一个

        try {
            file.transferTo(path);
            map.put("data", CollUtil.newArrayList(Dict.create().set("url", SERVER_PREFIX+"cover/"+name)));
            map.put("errno", 0);
            System.out.println("上传成功"+map.get("data"));
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("errno", 1);
            return map;
        }
    }

    // 获取文件的后缀名
    private String getSuffix(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        return fileSuffix;
    }
}